package com.giftmail.handler

import com.giftmail.message.RegisterMsg
import io.netty.buffer.{ByteBuf, Unpooled}
import io.netty.channel.{ChannelHandlerContext, ChannelInboundHandlerAdapter}

class ServerHandler extends ChannelInboundHandlerAdapter{

  /**
    * 有客户端建立连接后调用
    * @param ctx
    */
  override def channelActive(ctx: ChannelHandlerContext):Unit = {
    println("一个客户端连接上了..........")
  }

  /**
    * 接受客户端发送来的消息
    * @param ctx
    * @param msg
    */
  override def channelRead(ctx: ChannelHandlerContext, msg: scala.Any):Unit = {
    println("收到客户端发送的消息了")
//    val byteBuf = msg.asInstanceOf[ByteBuf]
//    val bytes = new Array[Byte](byteBuf.readableBytes())
//    byteBuf.readBytes(bytes)
//    val message = new String(bytes,"UTF-8")
//    println(message)
//
//    //返回给客户端一段消息
//    val back = "Good Boy"
//    val resp = Unpooled.copiedBuffer(back.getBytes("UTF-8"))
    //改造:第二步
    println(msg)
//    val result = msg match {
//      case RegisterMsg(msg) =>{
//        def resOk(n:String):String = {
//            val r= "ok"
//            r
//          r
//        }
//      }
//    }
//
//    ctx.write(result)
  }

  /**
    * 将消息队列中的数据写入到SocketChannel后,发回给客户端
    * @param ctx
    */
  override def channelReadComplete(ctx: ChannelHandlerContext) :Unit = {
    println("channelReadComplete invoke")
    ctx.flush()
  }

  /**
    * 发生异常关闭ChannelHandlerContext
    * @param ctx
    * @param cause
    */
  override def exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) :Unit= {
    println("exceptionCaught invoke")
    ctx.close()
  }
}
